using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SimpleTongHuaShunQuery
{
    /// <summary>
    /// 查询资金股票程序
    /// </summary>
    class QueryFundsStocks
    {
        #region Windows API 声明
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);

        [DllImport("kernel32.dll")]
        static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

        [DllImport("kernel32.dll")]
        static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr hObject);

        [DllImport("user32.dll")]
        static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll")]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll")]
        static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern int GetDlgCtrlID(IntPtr hWndCtl);

        [DllImport("user32.dll")]
        static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [DllImport("user32.dll")]
        static extern IntPtr SetFocus(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern IntPtr GetParent(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, StringBuilder lParam);

        [DllImport("kernel32.dll")]
        static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);

        [DllImport("kernel32.dll")]
        static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

        [DllImport("kernel32.dll")]
        static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint dwFreeType);

        [DllImport("kernel32.dll")]
        static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, out uint lpNumberOfBytesWritten);

        [DllImport("kernel32.dll")]
        static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, out uint lpNumberOfBytesRead);

        const int SW_RESTORE = 9;
        const int SW_SHOW = 5;
        const uint TH32CS_SNAPPROCESS = 0x00000002;
        const uint WM_CLOSE = 0x0010;

        // TreeView 消息
        const uint TVM_GETNEXTITEM = 0x110A;
        const uint TVM_EXPAND = 0x1102;
        const uint TVM_SELECTITEM = 0x110B;
        const uint TVM_GETITEM = 0x110C;
        const uint TVGN_ROOT = 0x0000;
        const uint TVGN_NEXT = 0x0001;
        const uint TVGN_CHILD = 0x0004;
        const uint TVGN_FIRSTVISIBLE = 0x0005;
        const uint TVE_EXPAND = 0x0002;
        const uint TVIF_TEXT = 0x0001;
        const uint TVIF_HANDLE = 0x0010;

        // 进程权限
        const uint PROCESS_VM_OPERATION = 0x0008;
        const uint PROCESS_VM_READ = 0x0010;
        const uint PROCESS_VM_WRITE = 0x0020;
        const uint MEM_COMMIT = 0x1000;
        const uint MEM_RELEASE = 0x8000;
        const uint PAGE_READWRITE = 0x04;

        [StructLayout(LayoutKind.Sequential)]
        public struct PROCESSENTRY32
        {
            public uint dwSize;
            public uint cntUsage;
            public uint th32ProcessID;
            public IntPtr th32DefaultHeapID;
            public uint th32ModuleID;
            public uint cntThreads;
            public uint th32ParentProcessID;
            public int pcPriClassBase;
            public uint dwFlags;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szExeFile;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left, Top, Right, Bottom;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct TVITEM
        {
            public uint mask;
            public IntPtr hItem;
            public uint state;
            public uint stateMask;
            public IntPtr pszText;
            public int cchTextMax;
            public int iImage;
            public int iSelectedImage;
            public int cChildren;
            public IntPtr lParam;
        }

        public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
        public delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);
        #endregion

        static void Main(string[] args)
        {
            Console.WriteLine("🚀 同花顺查询程序 - 资金股票查询");
            Console.WriteLine("📋 功能: 打开菜单栏中的查询[F4]->资金股票");
            Console.WriteLine("🔧 使用新的定位方法: AutomationId=129定位树控件");
            Console.WriteLine();

            try
            {
                // 执行查询资金股票操作
                ExecuteQueryFundsStocks();
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 程序异常: " + ex.Message);
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }

        /// <summary>
        /// 执行查询资金股票操作
        /// </summary>
        static void ExecuteQueryFundsStocks()
        {
            try
            {
                Console.WriteLine("🚀 开始执行查询资金股票操作");
                
                // 1. 连接到xiadan.exe进程
                Console.WriteLine("🔍 步骤1: 连接GUI程序");
                uint processId = FindProcessByName("xiadan.exe");
                if (processId == 0)
                {
                    Console.WriteLine("❌ 未找到xiadan.exe进程，请确保同花顺程序正在运行");
                    return;
                }
                Console.WriteLine("✅ 连接成功，PID: " + processId);

                // 2. 关掉多余对话框
                Console.WriteLine();
                Console.WriteLine("🔍 步骤2: 关掉多余对话框");
                int closedCount = ClosePopupDialogs(processId);
                Console.WriteLine("✅ 关闭了 " + closedCount + " 个弹出框");

                // 3. 查找主窗口并激活
                Console.WriteLine();
                Console.WriteLine("🔍 步骤3: 查找并激活主窗口");
                IntPtr mainWindow = FindMainWindow(processId);
                if (mainWindow == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到主窗口");
                    return;
                }
                Console.WriteLine("✅ 找到主窗口");

                // 激活并恢复窗口
                Console.WriteLine("🔄 正在恢复和激活窗口...");
                
                // 先检查窗口是否最小化
                RECT mainRect;
                if (GetWindowRect(mainWindow, out mainRect))
                {
                    if (mainRect.Left < -1000 || mainRect.Top < -1000)
                    {
                        Console.WriteLine("⚠️ 检测到窗口被最小化，正在恢复...");
                        ShowWindow(mainWindow, SW_RESTORE);
                        Thread.Sleep(100);
                    }
                }
                
                ShowWindow(mainWindow, SW_SHOW);
                SetForegroundWindow(mainWindow);

                // 4. 使用新的定位方法查找树控件
                Console.WriteLine();
                Console.WriteLine("🔍 步骤4: 使用AutomationId=129定位树控件");
                IntPtr treeView = FindTreeViewByAutomationId(mainWindow, 129);
                if (treeView == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到AutomationId=129的树控件");
                    return;
                }
                Console.WriteLine("✅ 成功找到树控件 (句柄: 0x" + treeView.ToString("X") + ")");

                // 5. 点击树控件以激活它
                Console.WriteLine();
                Console.WriteLine("🔍 步骤5: 点击树控件激活焦点");
                bool clickSuccess = ClickTreeViewToActivate(treeView);
                if (clickSuccess)
                {
                    Console.WriteLine("✅ 树控件点击激活成功");
                }
                else
                {
                    Console.WriteLine("⚠️ 树控件点击激活失败，继续尝试导航");
                }

                // 6. 导航到查询->资金股票
                Console.WriteLine();
                Console.WriteLine("🔍 步骤6: 导航菜单 查询[F4] -> 资金股票");
                bool success = NavigateToQueryFundsStocks(treeView, processId);
                
                if (success)
                {
                    Console.WriteLine("✅ 成功打开 查询[F4] -> 资金股票");
                    Console.WriteLine("🎉 查询资金股票操作完成！");
                }
                else
                {
                    Console.WriteLine("❌ 菜单导航失败");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 执行查询资金股票异常: " + ex.Message);
            }
            finally
            {
                Console.WriteLine("📝 查询资金股票操作处理完成");
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }

        /// <summary>
        /// 根据进程名查找进程ID
        /// </summary>
        static uint FindProcessByName(string processName)
        {
            IntPtr hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
            if (hProcessSnap == IntPtr.Zero)
                return 0;

            PROCESSENTRY32 pe32 = new PROCESSENTRY32();
            pe32.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));

            if (!Process32First(hProcessSnap, ref pe32))
            {
                CloseHandle(hProcessSnap);
                return 0;
            }

            do
            {
                if (pe32.szExeFile.Equals(processName, StringComparison.OrdinalIgnoreCase))
                {
                    CloseHandle(hProcessSnap);
                    return pe32.th32ProcessID;
                }
            } while (Process32Next(hProcessSnap, ref pe32));

            CloseHandle(hProcessSnap);
            return 0;
        }

        /// <summary>
        /// 关闭弹出对话框
        /// </summary>
        static int ClosePopupDialogs(uint processId)
        {
            int closedCount = 0;

            EnumWindows((hWnd, lParam) =>
            {
                uint windowProcessId;
                GetWindowThreadProcessId(hWnd, out windowProcessId);
                if (windowProcessId == processId && IsWindowVisible(hWnd))
                {
                    StringBuilder className = new StringBuilder(256);
                    GetClassName(hWnd, className, className.Capacity);
                    string windowClass = className.ToString();

                    StringBuilder title = new StringBuilder(256);
                    GetWindowText(hWnd, title, title.Capacity);
                    string windowTitle = title.ToString();

                    // 关闭类型为#32770的对话框（但不关闭主窗口）
                    if (windowClass == "#32770" && !windowTitle.Contains("网上股票交易系统"))
                    {
                        Console.WriteLine("🗑️ 关闭弹出框: \"" + windowTitle + "\"");
                        SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                        closedCount++;
                    }
                }
                return true;
            }, IntPtr.Zero);

            return closedCount;
        }

        /// <summary>
        /// 查找主窗口
        /// </summary>
        static IntPtr FindMainWindow(uint processId)
        {
            IntPtr result = IntPtr.Zero;

            EnumWindows((hWnd, lParam) =>
            {
                uint windowProcessId;
                GetWindowThreadProcessId(hWnd, out windowProcessId);
                if (windowProcessId == processId && IsWindowVisible(hWnd))
                {
                    StringBuilder title = new StringBuilder(256);
                    GetWindowText(hWnd, title, title.Capacity);
                    string windowTitle = title.ToString();

                    if (windowTitle.Contains("网上股票交易系统"))
                    {
                        Console.WriteLine("📋 主窗口: \"" + windowTitle + "\"");
                        result = hWnd;
                        return false; // 停止枚举
                    }
                }
                return true;
            }, IntPtr.Zero);

            return result;
        }

        /// <summary>
        /// 通过AutomationId查找树控件（新的定位方法）
        /// </summary>
        static IntPtr FindTreeViewByAutomationId(IntPtr mainWindow, int automationId)
        {
            Console.WriteLine("🔍 使用新的定位方法: 通过AutomationId=" + automationId + "查找树控件");
            IntPtr result = IntPtr.Zero;

            // 直接枚举子窗口，查找匹配的树控件
            EnumChildWindows(mainWindow, (hWnd, lParam) =>
            {
                StringBuilder className = new StringBuilder(256);
                GetClassName(hWnd, className, className.Capacity);
                string controlClass = className.ToString();

                // 检查是否为SysTreeView32类型的控件
                if (controlClass == "SysTreeView32")
                {
                    int controlId = GetDlgCtrlID(hWnd);
                    
                    // 获取控件位置信息用于验证
                    RECT rect;
                    if (GetWindowRect(hWnd, out rect))
                    {
                        int width = rect.Right - rect.Left;
                        int height = rect.Bottom - rect.Top;
                        
                        Console.WriteLine("🔍 找到树控件: AutomationId=" + controlId + ", 类型=" + controlClass);
                        Console.WriteLine("📍 位置: [" + rect.Left + "," + rect.Top + "," + rect.Right + "," + rect.Bottom + "] 尺寸: " + width + "x" + height);
                        
                        // 精确匹配AutomationId=129
                        if (controlId == automationId)
                        {
                            Console.WriteLine("✅ 精确匹配AutomationId=" + automationId + "的树控件");
                            Console.WriteLine("📋 验证属性:");
                            Console.WriteLine("   - ClassName: " + controlClass);
                            Console.WriteLine("   - AutomationId: " + controlId);
                            Console.WriteLine("   - BoundingRectangle: [l=" + rect.Left + ",t=" + rect.Top + ",r=" + rect.Right + ",b=" + rect.Bottom + "]");
                            Console.WriteLine("   - LogicalSize: [w=" + width + ",h=" + height + "]");
                            
                            result = hWnd;
                            return false; // 停止枚举
                        }
                    }
                }
                return true;
            }, IntPtr.Zero);

            // 如果直接子窗口没找到，递归搜索
            if (result == IntPtr.Zero)
            {
                Console.WriteLine("🔍 在子窗口中递归搜索树控件...");
                EnumChildWindows(mainWindow, (hWnd, lParam) =>
                {
                    IntPtr childResult = FindTreeViewByAutomationId(hWnd, automationId);
                    if (childResult != IntPtr.Zero)
                    {
                        result = childResult;
                        return false; // 停止枚举
                    }
                    return true;
                }, IntPtr.Zero);
            }

            if (result == IntPtr.Zero)
            {
                Console.WriteLine("❌ 未找到AutomationId=" + automationId + "的树控件");
            }

            return result;
        }

        /// <summary>
        /// 点击树控件以激活它
        /// </summary>
        static bool ClickTreeViewToActivate(IntPtr treeView)
        {
            try
            {
                Console.WriteLine("🖱️ 正在点击树控件激活焦点...");
                
                // 获取树控件的位置
                RECT treeRect;
                if (!GetWindowRect(treeView, out treeRect))
                {
                    Console.WriteLine("❌ 无法获取树控件位置");
                    return false;
                }
                
                Console.WriteLine("📍 树控件位置: [" + treeRect.Left + "," + treeRect.Top + "," + treeRect.Right + "," + treeRect.Bottom + "]");
                
                // 计算树控件中心点
                int centerX = (treeRect.Left + treeRect.Right) / 2;
                int centerY = (treeRect.Top + treeRect.Bottom) / 2;
                
                // 稍微偏向左上角一点，避免点击到滚动条
                int clickX = treeRect.Left + (treeRect.Right - treeRect.Left) / 4;
                int clickY = treeRect.Top + (treeRect.Bottom - treeRect.Top) / 4;
                
                Console.WriteLine("🎯 点击位置: (" + clickX + ", " + clickY + ")");
                
                // 先设置焦点到树控件
                SetFocus(treeView);
                Thread.Sleep(100);
                
                // 发送鼠标点击消息到树控件
                // 使用相对于控件的坐标
                int relativeX = clickX - treeRect.Left;
                int relativeY = clickY - treeRect.Top;
                
                Console.WriteLine("📍 相对坐标: (" + relativeX + ", " + relativeY + ")");
                
                IntPtr lParam = (IntPtr)((relativeY << 16) | (relativeX & 0xFFFF));
                
                // 发送鼠标按下和释放消息
                const uint WM_LBUTTONDOWN = 0x0201;
                const uint WM_LBUTTONUP = 0x0202;
                
                Console.WriteLine("📤 发送鼠标点击消息");
                SendMessage(treeView, WM_LBUTTONDOWN, (IntPtr)1, lParam);
                Thread.Sleep(50);
                SendMessage(treeView, WM_LBUTTONUP, IntPtr.Zero, lParam);
                
                // 再次确保焦点
                SetFocus(treeView);
                Thread.Sleep(200);
                
                Console.WriteLine("✅ 树控件点击操作完成");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 点击树控件异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 导航到查询->资金股票
        /// </summary>
        static bool NavigateToQueryFundsStocks(IntPtr treeView, uint processId)
        {
            Console.WriteLine("🎯 开始导航到查询[F4]->资金股票");
            
            // 导航菜单路径: ["查询[F4]", "资金股票"]
            return NavigateTreeMenu(treeView, new string[] { "查询[F4]", "资金股票" }, processId);
        }

        /// <summary>
        /// 导航TreeView菜单
        /// </summary>
        static bool NavigateTreeMenu(IntPtr treeView, string[] menuPath, uint processId)
        {
            Console.WriteLine("🎯 导航路径: [" + string.Join(" -> ", menuPath) + "]");

            IntPtr currentItem = IntPtr.Zero;

            for (int i = 0; i < menuPath.Length; i++)
            {
                string targetMenu = menuPath[i];
                Console.WriteLine("🔍 查找: \"" + targetMenu + "\"");

                // 使用新的文本匹配方法查找节点
                IntPtr foundItem = FindTreeItemByText(treeView, targetMenu, currentItem, processId);
                if (foundItem == IntPtr.Zero)
                {
                    Console.WriteLine("❌ 未找到: \"" + targetMenu + "\"");
                    return false;
                }

                Console.WriteLine("✅ 找到: \"" + targetMenu + "\"");
                currentItem = foundItem;

                if (i < menuPath.Length - 1)
                {
                    // 展开项目
                    Console.WriteLine("📂 展开: " + targetMenu);
                    SendMessage(treeView, TVM_EXPAND, (IntPtr)TVE_EXPAND, currentItem);
                    Thread.Sleep(500); // 增加等待时间，确保展开完成
                }
                else
                {
                    // 点击最终项目（而不是仅仅选择）
                    Console.WriteLine("🖱️ 点击: " + targetMenu + " (句柄: 0x" + currentItem.ToString("X") + ")");
                    
                    // 先选择项目
                    const uint TVGN_CARET = 0x0009;
                    IntPtr result1 = SendMessage(treeView, TVM_SELECTITEM, (IntPtr)TVGN_CARET, currentItem);
                    Console.WriteLine("📋 TVM_SELECTITEM 结果: 0x" + result1.ToString("X"));
                    Thread.Sleep(100);
                    
                    // 然后点击项目来激活功能
                    bool clickSuccess = ClickTreeViewItem(treeView, currentItem);
                    if (clickSuccess)
                    {
                        Console.WriteLine("✅ 成功点击: " + targetMenu);
                    }
                    else
                    {
                        Console.WriteLine("⚠️ 点击失败: " + targetMenu);
                    }
                    
                    Thread.Sleep(500); // 等待界面响应
                }
            }

            return true;
        }

        /// <summary>
        /// 点击TreeView中的特定项目
        /// </summary>
        static bool ClickTreeViewItem(IntPtr treeView, IntPtr hItem)
        {
            try
            {
                Console.WriteLine("🖱️ 正在点击树节点...");
                
                // 获取树控件的位置
                RECT treeRect;
                if (!GetWindowRect(treeView, out treeRect))
                {
                    Console.WriteLine("❌ 无法获取树控件位置");
                    return false;
                }
                
                // 发送双击消息到树节点
                // 使用树控件的中心位置作为点击位置
                int clickX = treeRect.Left + (treeRect.Right - treeRect.Left) / 3;
                int clickY = treeRect.Top + (treeRect.Bottom - treeRect.Top) / 3;
                
                // 计算相对坐标
                int relativeX = clickX - treeRect.Left;
                int relativeY = clickY - treeRect.Top;
                
                IntPtr lParam = (IntPtr)((relativeY << 16) | (relativeX & 0xFFFF));
                
                Console.WriteLine("📍 点击相对坐标: (" + relativeX + ", " + relativeY + ")");
                
                // 发送双击消息来激活树节点功能
                const uint WM_LBUTTONDBLCLK = 0x0203;
                const uint WM_LBUTTONDOWN = 0x0201;
                const uint WM_LBUTTONUP = 0x0202;
                
                Console.WriteLine("📤 发送双击消息激活节点功能");
                
                // 先发送单击
                SendMessage(treeView, WM_LBUTTONDOWN, (IntPtr)1, lParam);
                Thread.Sleep(50);
                SendMessage(treeView, WM_LBUTTONUP, IntPtr.Zero, lParam);
                Thread.Sleep(100);
                
                // 再发送双击
                SendMessage(treeView, WM_LBUTTONDBLCLK, (IntPtr)1, lParam);
                Thread.Sleep(100);
                
                Console.WriteLine("✅ 树节点点击操作完成");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("❌ 点击树节点异常: " + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取TreeView节点的文本内容
        /// </summary>
        static string GetTreeItemText(IntPtr treeView, IntPtr hItem, uint processId)
        {
            try
            {
                // 打开目标进程
                IntPtr hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, processId);
                if (hProcess == IntPtr.Zero)
                {
                    return "";
                }

                // 在目标进程中分配内存
                const int bufferSize = 260;
                IntPtr remoteBuffer = VirtualAllocEx(hProcess, IntPtr.Zero, bufferSize, MEM_COMMIT, PAGE_READWRITE);
                if (remoteBuffer == IntPtr.Zero)
                {
                    CloseHandle(hProcess);
                    return "";
                }

                IntPtr remoteTVITEM = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)Marshal.SizeOf(typeof(TVITEM)), MEM_COMMIT, PAGE_READWRITE);
                if (remoteTVITEM == IntPtr.Zero)
                {
                    VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
                    CloseHandle(hProcess);
                    return "";
                }

                // 准备TVITEM结构
                TVITEM tvItem = new TVITEM();
                tvItem.mask = TVIF_TEXT | TVIF_HANDLE;
                tvItem.hItem = hItem;
                tvItem.pszText = remoteBuffer;
                tvItem.cchTextMax = bufferSize;

                // 将TVITEM写入目标进程内存
                IntPtr localTVITEM = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TVITEM)));
                Marshal.StructureToPtr(tvItem, localTVITEM, false);

                uint bytesWritten;
                if (!WriteProcessMemory(hProcess, remoteTVITEM, localTVITEM, (uint)Marshal.SizeOf(typeof(TVITEM)), out bytesWritten))
                {
                    Marshal.FreeHGlobal(localTVITEM);
                    VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
                    VirtualFreeEx(hProcess, remoteTVITEM, 0, MEM_RELEASE);
                    CloseHandle(hProcess);
                    return "";
                }

                // 发送TVM_GETITEM消息
                IntPtr result = SendMessage(treeView, TVM_GETITEM, IntPtr.Zero, remoteTVITEM);
                
                if (result != IntPtr.Zero)
                {
                    // 读取文本内容
                    IntPtr localBuffer = Marshal.AllocHGlobal(bufferSize);
                    uint bytesRead;
                    if (ReadProcessMemory(hProcess, remoteBuffer, localBuffer, bufferSize, out bytesRead))
                    {
                        string text = Marshal.PtrToStringAuto(localBuffer);
                        Marshal.FreeHGlobal(localBuffer);
                        Marshal.FreeHGlobal(localTVITEM);
                        VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
                        VirtualFreeEx(hProcess, remoteTVITEM, 0, MEM_RELEASE);
                        CloseHandle(hProcess);
                        return text ?? "";
                    }
                    Marshal.FreeHGlobal(localBuffer);
                }

                Marshal.FreeHGlobal(localTVITEM);
                VirtualFreeEx(hProcess, remoteBuffer, 0, MEM_RELEASE);
                VirtualFreeEx(hProcess, remoteTVITEM, 0, MEM_RELEASE);
                CloseHandle(hProcess);
                return "";
            }
            catch (Exception ex)
            {
                Console.WriteLine("⚠️ 获取节点文本异常: " + ex.Message);
                return "";
            }
        }

        /// <summary>
        /// 通过文本名称查找TreeView节点
        /// </summary>
        static IntPtr FindTreeItemByText(IntPtr treeView, string targetText, IntPtr parentItem, uint processId)
        {
            IntPtr currentItem;
            
            if (parentItem == IntPtr.Zero)
            {
                // 从根节点开始搜索
                currentItem = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_ROOT, IntPtr.Zero);
            }
            else
            {
                // 从指定父节点的第一个子节点开始搜索
                currentItem = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_CHILD, parentItem);
            }

            while (currentItem != IntPtr.Zero)
            {
                string itemText = GetTreeItemText(treeView, currentItem, processId);
                Console.WriteLine("🔍 检查节点: \"" + itemText + "\"");
                
                if (itemText == targetText)
                {
                    Console.WriteLine("✅ 找到匹配节点: \"" + itemText + "\"");
                    return currentItem;
                }

                // 检查下一个兄弟节点
                currentItem = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_NEXT, currentItem);
            }

            Console.WriteLine("❌ 未找到匹配节点: \"" + targetText + "\"");
            return IntPtr.Zero;
        }

        /// <summary>
        /// 查找TreeView项目（智能定位方法）
        /// </summary>
        static IntPtr FindTreeItem(IntPtr treeView, string targetText, IntPtr parentItem)
        {
            if (targetText == "查询[F4]")
            {
                // 查询[F4]通常在菜单的特定位置，我们可以通过遍历根项目来查找
                Console.WriteLine("🎯 智能定位查询[F4]菜单项");
                IntPtr rootItem = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_ROOT, IntPtr.Zero);
                IntPtr currentItem = rootItem;
                
                Console.WriteLine("🔍 根项目句柄: 0x" + rootItem.ToString("X"));
                
                // 遍历所有根级项目，查找包含"查询"的项目
                int itemIndex = 0;
                while (currentItem != IntPtr.Zero)
                {
                    itemIndex++;
                    Console.WriteLine("🔍 检查第" + itemIndex + "个项目句柄: 0x" + currentItem.ToString("X"));
                    
                    // 这里可以添加获取项目文本的逻辑来验证是否为"查询[F4]"
                    // 由于TreeView文本获取比较复杂，我们先尝试基于位置的方法
                    
                    // 查询菜单通常在第2-4个位置，我们可以尝试这些位置
                    if (itemIndex >= 2 && itemIndex <= 4)
                    {
                        Console.WriteLine("🎯 尝试第" + itemIndex + "个项目作为查询菜单");
                        return currentItem;
                    }
                    
                    currentItem = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_NEXT, currentItem);
                }
                
                // 如果没找到，返回第3个项目作为默认（通常查询在这个位置）
                currentItem = rootItem;
                for (int i = 1; i < 3 && currentItem != IntPtr.Zero; i++)
                {
                    currentItem = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_NEXT, currentItem);
                }
                Console.WriteLine("🎯 默认选择第3个项目作为查询菜单: 0x" + currentItem.ToString("X"));
                return currentItem;
            }
            else if (targetText == "资金股票" && parentItem != IntPtr.Zero)
            {
                // 资金股票是查询菜单的子项
                Console.WriteLine("🔍 查找父项目 0x" + parentItem.ToString("X") + " 的子项目");
                IntPtr firstChild = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_CHILD, parentItem);
                Console.WriteLine("🎯 第一个子项目句柄: 0x" + firstChild.ToString("X"));
                
                if (firstChild == IntPtr.Zero)
                {
                    Console.WriteLine("⚠️ 未找到子项目，可能需要先展开父项目");
                    return IntPtr.Zero;
                }
                
                // 资金股票通常是查询菜单的第一个或第二个子项
                // 我们先返回第一个子项，如果不对可以调整为下一个
                IntPtr targetChild = firstChild;
                
                // 也可以尝试第二个子项
                // IntPtr secondChild = (IntPtr)SendMessage(treeView, TVM_GETNEXTITEM, (IntPtr)TVGN_NEXT, firstChild);
                // if (secondChild != IntPtr.Zero)
                // {
                //     Console.WriteLine("🎯 第二个子项目句柄: 0x" + secondChild.ToString("X"));
                //     targetChild = secondChild;
                // }
                
                Console.WriteLine("🎯 选择资金股票子项目: 0x" + targetChild.ToString("X"));
                return targetChild;
            }

            Console.WriteLine("❌ 未知菜单项: " + targetText);
            return IntPtr.Zero;
        }
    }

}
